﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using StackExchange.Redis;

namespace HelperCommon.AOP.RedisCache
{
    public class RedisCaching : IRedisCaching
    {
        private readonly ConnectionMultiplexer redis;
        private readonly IDatabase database;
        public RedisCaching(ConnectionMultiplexer _redis)
        {
            this.redis = _redis;
            database = _redis.GetDatabase();
        }
        /// <summary>
        /// 获取值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public  string GetValue(string key)
        {
            return  database.StringGet(key);
        }
        /// <summary>
        /// 存储值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="cacheTime">过期时间</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public  void Set(string key, object value, TimeSpan cacheTime)
        {
            if (value != null)
            {
                if (value is string cacheValue)
                {
                    // 字符串无需序列化
                     database.StringSetAsync(key, cacheValue, cacheTime);
                }
                else
                {
                    //序列化，将object值生成RedisValue
                     database.StringSetAsync(key, JsonSerializer.Serialize(value), cacheTime);
                }
            }
        }
    }
}
